export const isWebAdmin = state => state.currentUser.admin;

export const isSpaceAdmin = state => state.currentSpace.admins
  .map(user => user.id)
  .includes(state.currentUser.id);

export const isSpaceOwner = state => state.currentUser.id === state.currentSpace.owner.id;

export const isDocAuthor = state => state.currentUser.id === state.currentDocument.author.id;

export const isIssueAuthor = state => state.currentUser.id === state.currentIssue.author.id;

export const isGroupOwner = state => state.currentUser.id === state.currentGroup.owner.id;

export const isGroupAdmin = state => state.currentGroup.admins
  .map(user => user.id)
  .includes(state.currentUser.id);

export const whoseHomepage = (state) => {
  const showing = state.showingUser;
  const current = state.currentUser;
  if (showing.id === current.id) return '我';
  else if (showing.gender === 'male') return '他';
  else if (showing.gender === 'female') return '她';
  return 'Ta';
};

// 生成doc目录
export const docCatalog = (state) => {
  const element = document.createElement('div');
  const headerTags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  element.innerHTML = state.currentDocument.content;
  const headers = element.querySelectorAll(headerTags.join(','));

  // 根据 H1, H2 获取标签层级
  function headerIndex(header) {
    return Number(header.tagName.replace('H', ''));
  }

  const headersList = [];
  for (let i = 0; i < headers.length; i += 1) {
    headersList.push({
      index: i,
      headerIndex: headerIndex(headers[i]),
      contentAnchor: `data-doc-catalog-index-${i}`,
      textContent: headers[i].textContent,
      label: headers[i].textContent, // tree
      children: [], // tree
    });
  }
  // 从这里 return headersList 就是 doc-catalog.vue 注释的部分

  // [{ id: 1 }, { id: 2 }, { id: 4 }, { id: 3 }, { id: 2 }] =>
  // [{ id: 1, children: [{ id: 2, children: [{ id: 4 }, { id: 3 }]}, { id: 2 }]}]
  function intoTree(item, tree) {
    const lastTreeItem = tree.slice(-1)[0] || {};
    if (!lastTreeItem.headerIndex) {
      tree.push(Object.assign(lastTreeItem, item));
    } else if (lastTreeItem.headerIndex < item.headerIndex) { // h2 < h1
      intoTree(item, lastTreeItem.children);
    } else {
      tree.push(item);
    }
  }

  const headersTree = [];
  while (headersList.length) {
    const item = headersList.shift(); // 取出当前剩下的第一个
    intoTree(item, headersTree);
  }

  return headersTree;
};
